import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

import 'JsSDKFactory.dart';

/// FileName: WebView
///
/// @Author Jone
/// @Date 2024/7/3
/// @Description：WebView
class MyWebView extends StatefulWidget {
  final String url;

  const MyWebView({
    super.key,
    required this.url,
  });

  @override
  State<MyWebView> createState() => _MyWebViewState();
}

class _MyWebViewState extends State<MyWebView> {
  InAppWebViewGroupOptions? options;
  String _ua = "JinHua_JCY jcy_version:B";

  @override
  Widget build(BuildContext context) {
    options = InAppWebViewGroupOptions(
      //跨平台配置
      crossPlatform: InAppWebViewOptions(
        applicationNameForUserAgent: _ua,
        transparentBackground: true,
        // userAgent: _ua,
        allowUniversalAccessFromFileURLs: true,
        useShouldOverrideUrlLoading: true,
        useOnDownloadStart: true,
        resourceCustomSchemes: ["font"],
        // clearCache: true,
        verticalScrollBarEnabled: true,
        // cacheEnabled: true,
        useOnLoadResource: true,
        // //加载url拦截功能
        // useShouldInterceptAjaxRequest: true,
        // //ajax请求拦截
        // useOnLoadResource: false,
        //资源加载回调
        allowFileAccessFromFileURLs: false,
        //资源加载
        mediaPlaybackRequiresUserGesture: false,
        //多媒体控制
        javaScriptEnabled: true,
        javaScriptCanOpenWindowsAutomatically: true,
        useShouldInterceptFetchRequest: true,
        // disableHorizontalScroll: true,
      ),
      //Android平台配置
      android: AndroidInAppWebViewOptions(
          // disableDefaultErrorPage: true,
          // forceDark: AndroidForceDark.FORCE_DARK_AUTO,
          // mixedContentMode: AndroidMixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW,
          // safeBrowsingEnabled: false,
          overScrollMode: AndroidOverScrollMode.OVER_SCROLL_NEVER,
          useHybridComposition: true,
          useShouldInterceptRequest: true,
          blockNetworkImage: false,
          //支持https
          mixedContentMode: AndroidMixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW),
      //iOS平台配置
      ios: IOSInAppWebViewOptions(
        enableViewportScale: false,
        allowsInlineMediaPlayback: true,
        allowsBackForwardNavigationGestures: false,
        // automaticallyAdjustsScrollIndicatorInsets: true,
        // isFraudulentWebsiteWarningEnabled: false,
        // sharedCookiesEnabled: true,
      ),
    );
    return Scaffold(
      appBar: AppBar(
        title: const Text("WebView测试"),
      ),
      body: InAppWebView(
        initialOptions: options,
        initialUrlRequest: URLRequest(url: WebUri(widget.url ?? '')),
        onConsoleMessage: (_, message) {
          print("onConsole--->${message.message}");
        },
        onWebViewCreated: (ctrl){
          handleYDJsEvent(ctrl);
        },
        shouldOverrideUrlLoading: (controller,navigationAction) async{
          Uri? uri = navigationAction.request.url;
          print("shouldOverrideUrlLoading---->$uri");
          return NavigationActionPolicy.ALLOW;
        },
        gestureRecognizers: {
          Factory<OneSequenceGestureRecognizer>(
            () => LongPressGestureRecognizer(
                duration: const Duration(milliseconds: 200)),
          ),
        },
      ),
    );
  }

  ///jssdj监听js触发flutter动作
  void handleYDJsEvent(InAppWebViewController controller) {
    var jsSDKOptions = JsSDKOptions(
      context: context,
      userAgent: _ua,
      type: "",
      shareTitle: "",
      shareDesc: "",
      sharePicUrl: "",
      articleUrl: "",
      shareUrl: "",
      publishId: 0,
      pushId: 0,
      serviceId: 0,
      columnId: "",
      columnName: "",
      changeStatusBarStyle: (args) => {},
      backToCloseWeb: (args) => {},
      getLikeDetails: () => Future(() => null),
      requestAddLike: () => Future(() => null),
      saveImageByFlutter: (li) => Future(() => ""),
    );
    JsSDKFactory.init(controller, jsSDKOptions);
    JsSDKFactory().assembleController();
  }
}
